﻿#ifndef TCPCLIENTROBOT_H
#define TCPCLIENTROBOT_H

#include "BaseLib/EngineObject.h"

#include <QThread>

class QTcpSocket;
class QTimer;
class ProtocolStream;
//与策略中心的TCP连接管理线程
class TcpClientRobot : public EngineObject
{
    Q_OBJECT
public:
    TcpClientRobot(int id, EngineProject *project);
    static TcpClientRobot *getInstance() {return s_pInstance;}

    virtual bool init() override;
    void cleanup() override;
    //重写基类的虚函数
    void onStarted() override; //启停函数

    QString     robotIp() const {return m_serverIp.value().toString();}
    quint16     robotPort() const {return m_serverPort.value().toInt();}
    int         robotReconnInterval() const {return m_reconnInterval.value().toInt();}
    QString     robotStartCode() const {return m_start_code.value().toString();}
    QString     robotSplitCode() const {return m_split_code.value().toString();}
    QString     robotEndCode() const {return m_end_code.value().toString();}
    QStringList graspDevTypeList() const;   // 抓具类型描述

    /**\
    \brief  应答策略中心的消息
    */
    void        respondToTcpRobot(const QByteArray &rebotMsg);
    /**\
    \brief  向策略中心发送消息
    */
    void        sendToTcpRobot(const QByteArray &rebotMsg);

    /**\
    \brief  发送机器人运行指令
    \param[in]  坐标点xyz和法向量abc
    \param[in]  抓具类型(注意:从1开始)
    \return     返回拼接的指令
    */
    QString     sendRunCoord(const QList<double> &farray, int graspDevId);

signals:

private slots:
    void onConnected();
    void onDisconnected();
    void onTimeout();
    void setIntervalAsync(const int newValue, const int oldValue);

    void onReadyRead();
    void sendToTcpRobotAsync(const QByteArray &rebotMsg);

private:
    void resetTcpConfig();

    static TcpClientRobot *s_pInstance;

private:
    Attribute       m_serverIp;             //!< Server的IP
    Attribute       m_serverPort;           //!< Server的端口号
    Attribute       m_reconnInterval;       //!< Server重连间隔

    Attribute       m_start_code;
    Attribute       m_split_code;
    Attribute       m_end_code;
    Attribute       m_graspDevTypeList;     //!< 抓具类型描述列表

    QThread         m_thread;               //!< 独立线程
    QTcpSocket      *m_socket;              //!< TCP Socket
    QTimer          *m_timer;               //!< 定时器

};

#endif // TCPCLIENTROBOT_H
